<template>
    <el-upload 
    class="avatar-uploader"
    :before-upload="beforeAvatarUpload"
    :on-success="handleAvatarSuccess"
    @click="handleRemove"
    ref="upload"
    name="img"
    action="/api/upload/uploadImg" 
    :limit="1"
     list-type="picture-card"
     :show-file-list="false">

        <img v-if="imageUrl" :src="imageUrl" class="avatar" />
        <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
    </el-upload>

    <el-dialog v-model="dialogVisible">
        <img w-full :src="dialogImageUrl" alt="Preview Image" />
    </el-dialog>
</template>
<script setup>
import { ref,watchEffect} from 'vue'
import {  Plus, } from '@element-plus/icons-vue'
import { ElMessage} from 'element-plus'

const dialogImageUrl = ref('')
const dialogVisible = ref(false)
const disabled = ref(false)

// upload组件的引用
const upload =ref()
// 删除逻辑
const handleRemove = (file) => {
    // 调用upload组件的remove方法
    upload.value.handleRemove(file)
}


// 定义组件v-model默认接收的modelValue
let props =defineProps(["modelValue"])

watchEffect(()=>{
        imageUrl.value = props.modelValue
    
},{
    // 组件挂载的时候执行
    flush:'post'
})
// console.log(props);
// 定义emit事件
const emit = defineEmits(["update:modelValue"])




// 控制文件上传大小和格式
const beforeAvatarUpload = (rawFile) => {
    // 定义图片格式
    const rawType = ['image/jpeg', 'image/png', 'image/gif', 'image/webp','image/jpg']
  if (!rawType.includes(rawFile.type)) {
    ElMessage.error('上传的图片不是:'+rawType.join(',')+"格式")
    return false
  } else if (rawFile.size / 1024 / 1024 > 1) {
    ElMessage.error('图片上传大小不能超过 1MB!')
    return false
  }
    // console.log(rawFile)
  return true
}

// 文件上传成功
let imageUrl = ref('')
const handleAvatarSuccess = (response,uploadFile) => {imageUrl.value = URL.createObjectURL(uploadFile.raw)
    // 将上传成功之后服务器返回的结果中的图片地址，通过组件的model的形式传递给dialog组件中的from表单
    if(response.state){
        // 上传成功
        emit("update:modelValue",response.imgUrl)
    }else{
        // 上传失败
        ElMessage.error("上传失败")
    }
}

</script>

<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
  